package bankapplication.com.acme.bankapp.domain.bank;

import bankapplication.com.acme.bankapp.service.bank.EmailService;
import bankapplication.com.acme.exceptions.ClientExistsException;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Bank implements Serializable {
  private HashSet<Client> clients = new HashSet<Client>();
  private HashSet<ClientRegistrationListener> listeners;
  
  public Bank(HashSet<ClientRegistrationListener> listeners, HashSet<Client> clients, EmailService emailService) {
    this.listeners = listeners;
    class PrintClientListener implements ClientRegistrationListener, Serializable {
      @Override
      public void onClientAdded(Client c){
        c.getClientSaltation();
      }
    }
    class EmailNotificationListener implements ClientRegistrationListener, Serializable {
      
      private EmailService emailService;
      
      EmailNotificationListener(EmailService emailService){
        this.emailService = emailService; 
      }
      @Override
      public void onClientAdded(Client c){
        emailService.sendNotificationEmail(c, "clientEmailAddress");
      }
    }
    class DebugListener implements ClientRegistrationListener, Serializable {
      @Override
      public void onClientAdded(Client c){
        System.out.println(c.toString());
        System.out.println((new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS")).format(new Date()));
      }
    }
    listeners.add(new PrintClientListener());
    listeners.add(new EmailNotificationListener(emailService));
    listeners.add(new DebugListener());
    Iterator<Client> clientiter = clients.iterator();
    while(clientiter.hasNext()){
      Client currentclient = clientiter.next();
      try{
        addClient(currentclient);
      }
      catch(ClientExistsException e){
        Iterator<Account> accountiter = currentclient.getAcconts().iterator();
        while(accountiter.hasNext()){
          e.getExisitngClient().addAccount(accountiter.next());
        }
      }
    }
  }
  public Set<Client> getClients(){
    return Collections.unmodifiableSet(clients);
  }
  public void addClient(Client c) throws ClientExistsException{
    Iterator<Client> clientiter = clients.iterator();
      // XXX [MY] What is about 'clients.contains(c)' ?
    while(clientiter.hasNext()){
      Client currentclient = clientiter.next();
      if(currentclient.equals(c)){
        throw new ClientExistsException(currentclient);
      }
    }
    Iterator<ClientRegistrationListener> listeneriterator = listeners.iterator();
    while(listeneriterator.hasNext()){
      listeneriterator.next().onClientAdded(c);
    }
    clients.add(c);
  }
}
